package com.ruoyi.api.kehu.pay;


import com.ijpay.core.enums.SignType;
import com.ijpay.core.kit.WxPayKit;
import com.ijpay.wxpay.WxPayApi;
import com.ijpay.wxpay.model.RefundModel;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.SysConfigConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.pay.WxPayXiaoChengXuConfig;
import com.ruoyi.common.utils.CacheUtils;
import com.ruoyi.system.domain.JiajiaOrder;
import com.ruoyi.system.domain.JiajiaProxyApplication;
import com.ruoyi.system.domain.vo.TransferBillsVo;
import com.ruoyi.system.service.ApiPayService;
import com.ruoyi.system.service.IJiajiaOrderService;
import com.ruoyi.system.service.IJiajiaProxyApplicationService;
import com.ruoyi.system.utils.V3PayUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/api/pay")
@Api(tags = "支付相关接口")
public class ApiPayController {

    private static final Logger logger = LoggerFactory.getLogger(ApiPayController.class);


    @Autowired
    private WxPayXiaoChengXuConfig xiaoChengXuConfig;
    @Autowired
    private IJiajiaOrderService orderService;
    @Autowired
    private ApiPayService apiPayService;


    @Autowired
    private IJiajiaProxyApplicationService  iJiajiaProxyApplicationService;


    @ApiOperation("项目小程序支付接口")
    @PostMapping("/xiaoChengXuPay")
    public AjaxResult xiaoChengXuPay(@RequestParam String orderSn,@RequestParam(required = false) String jsCode){
        return apiPayService.xiaoChengXuPay(orderSn, jsCode);
    }


    @ApiOperation("代理小程序支付接口")
    @PostMapping("/xiaoChengXuProxyPay")
    public AjaxResult xiaoChengXuProxyPay(@RequestParam String id,@RequestParam(required = false) String jsCode){
        return apiPayService.xiaoChengXuProxyPay(id, jsCode);
    }

    @ApiOperation("商城小程序支付接口")
    @PostMapping("/xiaoChengXuMallPay")
    public AjaxResult xiaoChengXuMallPay(@RequestParam String id,@RequestParam(required = false) String jsCode){
        return apiPayService.xiaoChengXuMallPay(id, jsCode);
    }


    @ApiOperation("代理小程序退款接口")
    @PostMapping("/xiaoChengProxyRefund")
    public AjaxResult xiaoChengProxyRefund(@RequestParam Long id,@RequestParam(required = false) String  refundFee ,@RequestParam(required = false) String jsCode){

        JiajiaProxyApplication jiajiaProxyApplication = iJiajiaProxyApplicationService.selectJiajiaProxyApplicationById(Long.valueOf(id));
        String totalFee="";
        if(jiajiaProxyApplication.getType()==0){
            Object cost = CacheUtils.get(Constants.SYS_CONFIG_CACHE, Constants.SYS_CONFIG_KEY+ SysConfigConstants.sys_apply_promoter_cost);

            totalFee=cost.toString();

        }else{
            Object cost = CacheUtils.get(Constants.SYS_CONFIG_CACHE, Constants.SYS_CONFIG_KEY+SysConfigConstants.sys_apply_community_cost);

            totalFee=cost.toString();

        }
        if(refundFee == null ){
            refundFee=totalFee;
        }
        //这里是走小程序退款
        Map<String, String> params = RefundModel.builder()
                .appid(xiaoChengXuConfig.getAppid())
                .mch_id(xiaoChengXuConfig.getMachid())
                .nonce_str(WxPayKit.generateStr())
                .out_trade_no(jiajiaProxyApplication.getId().toString())
                .transaction_id(jiajiaProxyApplication.getTransactionId())
                .out_refund_no(WxPayKit.generateStr())
                .total_fee(totalFee)
                .refund_fee(refundFee)
                .notify_url(xiaoChengXuConfig.getNotifyUrl()+"/api/paynotify/refundNotify")
                .build()
                .createSign(xiaoChengXuConfig.getMckKey(), SignType.MD5);
        InputStream certIs = null;
        try {
            ClassPathResource classPathResource = new ClassPathResource(xiaoChengXuConfig.getKeyPath());
            certIs = classPathResource.getInputStream();
            logger.info(certIs.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        String refundStr = WxPayApi.orderRefundByProtocol(false, params, xiaoChengXuConfig.getKeyPath(), xiaoChengXuConfig.getMachid(),"");
        logger.info(refundStr);

        Map<String,String> map = WxPayKit.xmlToMap(refundStr);
        String returnCode = map.get("return_code");
        String resultCode = map.get("result_code");
        if (!resultCode.equals("SUCCESS") || !returnCode.equals("SUCCESS")){
            throw new RuntimeException("退款失败");
        }
        return AjaxResult.success();
    }



    @ApiOperation("商城小程序退款接口")
    @PostMapping("/xiaoChengXuMallRefund")
    public AjaxResult xiaoChengXuMallRefund(@RequestParam String id,@RequestParam(required = false) String jsCode){
        return apiPayService.xiaoChengXuMallRefund(id, jsCode);
    }

    @ApiOperation("项目服务小程序退款接口")
    @PostMapping("/xiaoChengXuFuWuRefund")
    public AjaxResult xiaoChengXuFuWuRefund(@RequestParam Long id,@RequestParam(required = false) String jsCode){

        JiajiaOrder order = orderService.selectJiajiaOrderById(id);

        //这里是走小程序退款
        Map<String, String> params = RefundModel.builder()
                .appid(xiaoChengXuConfig.getAppid())
                .mch_id(xiaoChengXuConfig.getMachid())
                .nonce_str(WxPayKit.generateStr())
                .out_trade_no(order.getOrderSn())
                .transaction_id(order.getTransactionId())
                .out_refund_no(order.getOrderSn())
                .total_fee(String.valueOf(order.getTotalPrice().multiply(new BigDecimal(100)).intValue()))
                .refund_fee(String.valueOf(order.getTotalPrice().multiply(new BigDecimal(100)).intValue()))
                .notify_url(xiaoChengXuConfig.getNotifyUrl()+"/api/paynotify/refundNotify")
                .build()
                .createSign(xiaoChengXuConfig.getMckKey(), SignType.MD5);
        InputStream certIs = null;
        try {
            ClassPathResource classPathResource = new ClassPathResource(xiaoChengXuConfig.getKeyPath());
            certIs = classPathResource.getInputStream();
            logger.info(certIs.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        String refundStr = WxPayApi.orderRefundByProtocol(false, params, xiaoChengXuConfig.getKeyPath(), xiaoChengXuConfig.getMachid(),"");
        logger.info(refundStr);

        Map<String,String> map = WxPayKit.xmlToMap(refundStr);
        String returnCode = map.get("return_code");
        String resultCode = map.get("result_code");
        if (!resultCode.equals("SUCCESS") || !returnCode.equals("SUCCESS")){
            throw new RuntimeException("退款失败");
        }
        return AjaxResult.success();
    }



    @ApiOperation("小程序充值接口")
    @PostMapping("/xiaoChengXuPayChongZhi")
    public AjaxResult xiaoChengXuPayChongZhi(@RequestParam String chongZhiSn,@RequestParam(required = false) String jsCode){
        return apiPayService.xiaoChengXuPayChongZhi(chongZhiSn,jsCode);
    }



    @ApiOperation("微信订单支付接口")
    @PostMapping("/weiXinPay")
    public AjaxResult weiXinPay(@RequestParam String orderSn,
                                @RequestParam String ip){
        return  apiPayService.weiXinPay(orderSn,ip);

    }

    @ApiOperation("微信充值接口")
    @PostMapping("/WxPayChongZhi")
    public AjaxResult WxPayChongZhi(@RequestParam String chongZhiSn,@RequestParam String ip){

        return  apiPayService.WxPayChongZhi(chongZhiSn,ip);
    }


    @ApiOperation("支付宝订单支付接口")
    @PostMapping("/zhiFuBaoPay")
    public AjaxResult zhiFuBaoPay(String orderSn) {
        return  apiPayService.zhiFuBaoPay(orderSn);

    }


    @ApiOperation("支付宝充值接口")
    @PostMapping("/zhiFuBaoChongZhiPay")
    public AjaxResult zhiFuBaoChongZhiPay(String chongZhiSn) {
        return apiPayService.zhiFuBaoChongZhiPay(chongZhiSn);
    }

    @ApiOperation("添加分账人")
    @PostMapping("/profitSharingAddReceiver")
    public AjaxResult profitSharingAddReceiver(String openid) {
        apiPayService.profitSharingAddReceiver( openid);
        return AjaxResult.success();
    }

    @ApiOperation("分账")
    @PostMapping("/profitSharing")
    public AjaxResult profitSharing(JiajiaOrder order , List<Map<String,String>> list) {
        apiPayService.profitSharing( order,list);
        return AjaxResult.success();
    }

    @ApiOperation("查询分账结果")
    @PostMapping("/profitsharingQuery")
    public AjaxResult profitsharingQuery(String orderSn ) {
        apiPayService.profitsharingQuery( orderSn);
        return AjaxResult.success();
    }


    @ApiOperation("分账回退")
    @PostMapping("/profitsharingReturn")
    public AjaxResult profitsharingReturn(@RequestParam String type,@RequestParam String orderSn ) {
        apiPayService.profitsharingReturn( orderSn,type);
        return AjaxResult.success();
    }

    @ApiOperation("查询分账回退结果")
    @PostMapping("/profitsharingReturnQuery")
    public AjaxResult profitsharingquery(String orderSn ) {
        apiPayService.profitsharingReturnQuery( orderSn);
        return AjaxResult.success();
    }



    @ApiOperation("手动分账或者自动分账")
    @PostMapping("/proxyProfitSharingByImpl")
    public AjaxResult proxyProfitSharingByImpl(String orderSn ) {

        return  apiPayService.proxyProfitSharingByImpl( orderSn);
    }
    @RequestMapping("/batchTransfer")
    @ResponseBody
    public AjaxResult batchTransfer(@RequestParam String transfer_amount,@RequestParam String openid) {
        TransferBillsVo transferBillsVo=new TransferBillsVo();

        return AjaxResult.success(V3PayUtil.createTransferBills(transferBillsVo));
    }


    /**
     * 提现
     * @param money
     * @return
     */
    @RequestMapping("/withdrawal")
    @ResponseBody
    public AjaxResult withdrawal(@RequestParam Integer money) {
        return AjaxResult.success(apiPayService.withdrawal(money));
    }


    /**
     * 提现
     * @param id
     * @return
     */
    @RequestMapping("/selectTransferAccounts")
    @ResponseBody
    public AjaxResult selectTransferAccounts(@RequestParam Long id) {
        return AjaxResult.success(apiPayService.selectTransferAccounts(id));
    }

}
